﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Infra.Utils.ExpressionTree
{
    public class QueryManager : IQueryManager
    {
        private readonly IDefaultValueRule _defaultValue;
        private readonly IQueryGenerator _methodPattern;

        public QueryManager(IDefaultValueRule defaultvalue, IQueryGenerator methodpattern)
        {
            this._defaultValue = defaultvalue;
            this._methodPattern = methodpattern; 
        }

        public void AddFilter(string propertyname, MethodType methodtype)
        {
            this._methodPattern[propertyname] = methodtype;
        }

        public IEnumerable<Func<T, bool>> Get<T>(T item)
        {
            foreach (var propertyInfo in item.GetType().GetProperties())
            {
                var value = propertyInfo.GetValue(item);

                if (this._defaultValue.IsDefault(value) == false)
                    yield return (Func<T, bool>)this._methodPattern.Generate(typeof(T), propertyInfo.Name, value).Compile();
            }
        }
    }
}
